import logging
import os
import time
import glob
from logging.handlers import RotatingFileHandler
from datetime import datetime

class PyLogger:
    def __init__(self):
        self.log_dir = "../logs" #日志目录
        self.max_size = 50 * 1024 * 1024  # 50MB
        self.max_files = 3 #最大文件夹
        self.max_files_to_keep = 50#最大文件
        self.logger = None

        # 确保日志目录存在
        os.makedirs(self.log_dir, exist_ok=True)

    def init_logger(self):
        # 生成带时间戳的日志文件名
        timestamp = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
        logfile_name = os.path.join(self.log_dir, f"daily_log_{timestamp}.log")

        # 创建RotatingFileHandler
        handler = RotatingFileHandler(
            logfile_name,
            maxBytes=self.max_size,
            backupCount=self.max_files
        )

        # 设置日志格式
        formatter = logging.Formatter(
            "[%(asctime)s.%(msecs)03d] [%(levelname)s] [Process %(process)d] [%(filename)s:%(lineno)d] %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S"
        )
        handler.setFormatter(formatter)

        # 创建logger实例
        self.logger = logging.getLogger("PyLogger")
        self.logger.setLevel(logging.DEBUG)
        self.logger.addHandler(handler)

        # 自动清理旧日志
        self._clean_old_logs()

        self.logger.info("Logger initialized")

    def _clean_old_logs(self):
        # 获取所有匹配的日志文件
        log_files = glob.glob(os.path.join(self.log_dir, "daily_log_*.log"))
        
        # 按创建时间排序（旧文件在前）
        log_files.sort(key=os.path.getctime)

        # 删除超出保留数量的文件
        while len(log_files) > self.max_files_to_keep:
            oldest = log_files.pop(0)
            try:
                os.remove(oldest)
                print(f"Deleted old log: {oldest}")
            except Exception as e:
                print(f"Failed to delete {oldest}: {str(e)}")

    def destroy_logger(self):
        if self.logger:
            handlers = self.logger.handlers[:]
            for handler in handlers:
                handler.close()
                self.logger.removeHandler(handler)
            logging.shutdown()
            print("Logger destroyed")

# 使用示例
if __name__ == "__main__":
    logger = PyLogger()
    logger.init_logger()
    
    try:
        logger.logger.debug("Debug message")
        logger.logger.info("Info message")
        logger.logger.warning("Warning message")
        logger.logger.error("Error message")
    finally:
        logger.destroy_logger()
